using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Forms;


using CStock;
using CUtil;

namespace CStock
{
	/// <summary>
	/// Summary description for QuoteWriter.
	/// </summary>
	public class QuoteUpdater
	{
		IProgramContext programContext;
        private WebYahoo dataFieldHandlerYahoo;


        public QuoteUpdater(IProgramContext myprogramContext)
		{

            this.programContext = myprogramContext;
            dataFieldHandlerYahoo = new WebYahoo();

			
		}
        public WebYahoo DatafeedHandlerYahoo
        {
            get
            {

                return this.dataFieldHandlerYahoo;
            }
        }
        private IPortfolio GetSpecialDataPortfolio_Index(string myPortfolioName)
        {
            switch (myPortfolioName)
            {
                case "Indexes Germany":
                    {
                        this.dataFieldHandlerYahoo.GetPortfolio_Index("Indexes Germany",
                        @"http://de.finance.yahoo.com/m8.php");
                        break;
                    }
                case "Indexes Europe":
                    {
                        this.dataFieldHandlerYahoo.GetPortfolio_Index("Indexes Europe",
                        @"http://de.finance.yahoo.com/m6.php");
                        break;
                    }
                case "Indexes World":
                    {
                        this.dataFieldHandlerYahoo.GetPortfolio_Index("Indexes World",
                        @"http://de.finance.yahoo.com/m2.php");
                        break;
                    }
                case "Indexes USA":
                    {
                        this.dataFieldHandlerYahoo.GetPortfolio_Index("Indexes USA",
                        @"http://de.finance.yahoo.com/m1.php");
                        break;
                    }
                case "Indexes DowJonesSTOXX":
                    {
                        this.dataFieldHandlerYahoo.GetPortfolio_Index("Indexes DowJonesSTOXX",
                        @"http://de.finance.yahoo.com/m7.php");
                        break;
                    }

            }
            return this.dataFieldHandlerYahoo.Portfolio;


        }
        private IPortfolio InitPortfolio(string portolfioID, string url_Overview, string url_Excel)
        {
            IPortfolio portf  = new Portfolio();
            portf.ID = portolfioID;
            //portfolio.Symbol = url_Overview;
            portf.URL_excelSheet = url_Excel;
            portf.URL_Overview = url_Overview;
            portf.Serialize();
            return portf;

        }
        
        public void UpdateStandardPorfolio_OnlyQuotes()
        {
            try
            {
                string myURL_Excel = this.programContext.TradeEconomy.Portfolio_Selected.URL_excelSheet;
                string myURL_Overview = this.programContext.TradeEconomy.Portfolio_Selected.URL_Overview;

                if (!String.IsNullOrEmpty(myURL_Overview))
                {
                    if (!String.IsNullOrEmpty(myURL_Excel))
                    {
                       

                        WebYahoo.Download_Portfolio_LastQuotes(this.programContext.TradeEconomy.Portfolio_Selected);

                    }
                    else
                    {
                        //it is a "index" portfolio
                        GetSpecialDataPortfolio_Index(this.programContext.TradeEconomy.Portfolio_Selected.ID);
                    }
                }

                else
                {
                    Debug.Assert(false, "URLs not set for " + this.programContext.TradeEconomy.Portfolio_Selected.ID);
                }

                //this.propertyGrid.Refresh();


            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in resetting portfolios " + ex.Message);
            }
        }
      
        private bool GetYahooQuotes(IDataItem di, bool inThread)
        {
            if (this.dataFieldHandlerYahoo.GetTimeSeriesFromYahoo_SingleShare(di, this.programContext.Configuration.Dates.DateMinWebupdate, inThread))
            {

                return true;
            }
            return false;
        }
        public bool UpdateSingleDataItemQuotes(IDataItem di, bool inThread)
        {
            string strType = di.WebStockType.ToString();
            if(strType.Contains("FED_"))
            {
                return GetQuotes_Special(di, inThread, false);
            }
            switch (di.WebStockType)
            {
                case CStock.Web.WebStockType.Yahoo:
                    {
                        return GetYahooQuotes(di, inThread);

                    }
                default:
                    {
                        return GetQuotes_Special(di, inThread, true);
                        //System.Windows.Forms.MessageBox.Show("SW Error - Website for update not known ");
                        //return false;
                    }
            }


        }
        private bool GetQuotes_Special(IDataItem di, bool inThread, bool bundesbank)
        {

            if (this.dataFieldHandlerYahoo.GetTimeSeries_Special(di,
                this.programContext.Configuration.Dates.DateMinWebupdate, inThread, bundesbank))
            {
                //this.propertyGrid.Refresh();
                return true;
            }
            return false;

        }

        public bool UpdateSingleDataItemQuotes(bool inThread)
        {

            return UpdateSingleDataItemQuotes(this.programContext.TradeEconomy.Portfolio_Selected.DataItem_Selected
                , inThread);

        }
        public bool CheckUpdateShare(IDataItem di)
        {
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;

            //no data available - 
            if (System.Windows.Forms.MessageBox.Show("Most likely no data available for '" + di.ID + "' ; do you want to update from web ?", "Update from Web ? ", buttons) == DialogResult.Yes)
            {
                //updateWebFinished = false;
                this.UpdateSingleDataItemQuotes(di, false);

                return true;


            }
            return false;
        }
        private void UpdatePortfolio(IPortfolio portf)
        {
            YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
            WebYahoo.Download_Portfolio_LastQuotes(portf);

        }
        private IPortfolio GetNasdaq()
        {
            IPortfolio portf = InitPortfolio("Nasdaq",
                     @"http://de.finance.yahoo.com/q/cp?s=%5EIXIC",
                    @"http://de.finance.yahoo.com/d/quotes.csv?s=@%5EIXIC&f=sl1d1t1c1ohgv&e=.csv");
            YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);

            for (int i = 1; i < 59; i++)
            {

                string urlOverview = @"http://uk.finance.yahoo.com/q/cp?s=%5EIXIC&c=" + i.ToString();
                portf.URL_Overview = urlOverview;
                System.Diagnostics.Debug.WriteLine("-- Getting data for page " + portf.URL_Overview);
                YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);


            }

            WebYahoo.Download_Portfolio_LastQuotes(portf);
            return portf ;
        }
        private IPortfolio GetNYSE()
        {
            IPortfolio portf = InitPortfolio("NYSE",
                     @"http://finance.yahoo.com/q/cp?s=%5ENYA",
                    @"http://download.finance.yahoo.com/d/quotes.csv?s=@%5ENYA&f=sl1d1t1c1ohgv&e=.csv&h=0");
            YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
            portf.URL_excelSheet_CommaSeparator = ",";

            for (int i = 1; i < 37; i++)
            {

                string urlOverview = @"http://finance.yahoo.com/q/cp?s=%5ENYA&c=" + i.ToString();
                portf.URL_Overview = urlOverview;
                System.Diagnostics.Debug.WriteLine("-- Getting data for page " + portf.URL_Overview);
                YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);


            }

            return portf;
        }
        public IPortfolio UpdatePortfolioFromWeb(string portfolioName)
        {
            
            IPortfolio portf = null;
            switch (portfolioName)
            {
                case "Dax":
                    {

                        portf = InitPortfolio("Dax",
              @"http://uk.finance.yahoo.com/q/cp?s=%5EGDAXI",
              @"http://de.finance.yahoo.com/d/quotes.csv?s=@%5EGDAXI&f=sl1d1t1c1ohgv&e=.csv");
                        YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
                        WebYahoo.Download_Portfolio_LastQuotes(portf);

                        break;
                    }
                case "Dow":
                    {
                        portf = InitPortfolio("Dow",
                  @"http://uk.finance.yahoo.com/q/cp?s=%5EDJI",
                   @"http://de.finance.yahoo.com/d/quotes.csv?s=@%5EDJI&f=sl1d1t1c1ohgv&e=.csv");
                        YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
                        WebYahoo.Download_Portfolio_LastQuotes(portf);
                        break;

                    }
                case "EuroSTOXX":
                    {
                        portf = InitPortfolio("EuroSTOXX",
             @"http://uk.finance.yahoo.com/q/cp?s=%5ESTOXX50E",
               @"http://de.finance.yahoo.com/d/quotes.csv?s=@%5ESTOXX50E&f=sl1d1t1c1ohgv&e=.csv");
                        YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
                        WebYahoo.Download_Portfolio_LastQuotes(portf);
                        break;

                    }
                case "MDax":
                    {


                        portf = InitPortfolio("MDax",
                          @"http://uk.finance.yahoo.com/q/cp?s=^MDAXI",
                            @"http://de.finance.yahoo.com/d/quotes.csv?s=@%5EMDAXI&f=sl1d1t1c1ohgv&e=.csv");
                        YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
                        WebYahoo.Download_Portfolio_LastQuotes(portf);

                        break;

                    }
                case "TecDax":
                    {


                        portf = InitPortfolio("TecDax",
                          @"http://uk.finance.yahoo.com/q/cp?s=^TECDAX",
                           @"http://de.old.finance.yahoo.com/d/quotes.csv?s=@%5ETECDAX&f=sl1d1t1c1ohgv&e=.csv");
                        YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);
                        WebYahoo.Download_Portfolio_LastQuotes(portf);

                        break;

                    }
                case "NYSE":
                    {
                        portf = GetNYSE();
                        
                        break;

                    }
                case "Nasdaq":
                    {
                        portf = GetNasdaq();
                        break;

                    }
                case "Indexes DowJonesSTOXX":
                    {
                        portf = GetSpecialDataPortfolio_Index("Indexes DowJonesSTOXX");
                        break;

                    }
                case "Indexes USA":
                    {
                        portf = GetSpecialDataPortfolio_Index("Indexes USA");
                        break;

                    }
                case "Indexes World":
                    {
                        portf = GetSpecialDataPortfolio_Index("Indexes World");
                        break;

                    }
                case "Indexes Europe":
                    {
                        portf = GetSpecialDataPortfolio_Index("Indexes Europe");
                        break;

                    }
                case "Indexes Germany":
                    {
                        portf = GetSpecialDataPortfolio_Index("Indexes Germany");
                        break;

                    }
             
                    
                    
            }
            if (portf != null)
            {
                portf.Serialize();
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("There is no index with this name available - this is a custom portfolio, the assets are custom items");
            }
            return portf;
        }

      
        public bool GetSpecialDataForPortfolio()
        {
            
            try
            {

                UpdatePortfolioFromWeb("Dax");
                UpdatePortfolioFromWeb("Dow");
                UpdatePortfolioFromWeb("EuroSTOXX");
                UpdatePortfolioFromWeb("MDax");
                UpdatePortfolioFromWeb("TecDax");

                UpdatePortfolioFromWeb("NYSE");
                UpdatePortfolioFromWeb("Nasdaq");
                UpdatePortfolioFromWeb("Indexes DowJonesSTOXX");
                UpdatePortfolioFromWeb("Indexes USA");
                UpdatePortfolioFromWeb("Indexes World");
                UpdatePortfolioFromWeb("Indexes Europe");
                UpdatePortfolioFromWeb("Indexes Germany");

            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in resetting portfolios " + ex.Message);
                return false;
            }
            return true;
        }

        #region fundamental Data

        public bool GetFundamentalData(IDataItem di, bool inThread)
        {
            if (this.dataFieldHandlerYahoo.GetTimeSeriesFromYahoo_SingleShare(di, this.programContext.Configuration.Dates.DateMinWebupdate, inThread))
            {

                return true;
            }

           
            return true;

        }

        #endregion
        public void UpdateStandardPorfolio_Names()
        {
            try
            {
                string myURL_Excel = this.programContext.TradeEconomy.Portfolio_Selected.URL_excelSheet;
                string myURL_Overview = this.programContext.TradeEconomy.Portfolio_Selected.URL_Overview;
                IPortfolio portf = this.programContext.TradeEconomy.Portfolio_Selected;

                if (!String.IsNullOrEmpty(myURL_Overview))
                {
                    if (!String.IsNullOrEmpty(myURL_Excel))
                    {
                        if (this.programContext.TradeEconomy.Portfolio_Selected.ID == "Nasdaq")
                        {

                            YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);

                            for (int i = 1; i < 59; i++)
                            {

                                string urlOverview = @"http://uk.finance.yahoo.com/q/cp?s=%5EIXIC&c=" + i.ToString();
                                portf.URL_Overview = urlOverview;
                                System.Diagnostics.Debug.WriteLine("-- Getting data for page " + portf.URL_Overview);
                                YahooFeedSockets.GetYahoo_ListOfStocks_DE(portf, true);


                            }
                        }
                        else
                        {
                            WebYahoo.Download_Portfolio_LastQuotes(portf);


                        }
                    }
                    else
                    {
                        //it is a "index" portfolio
                        GetSpecialDataPortfolio_Index(this.programContext.TradeEconomy.Portfolio_Selected.ID);
                    }
                }

                else
                {
                    Debug.Assert(false, "URLs not set for " + this.programContext.TradeEconomy.Portfolio_Selected.ID);
                }

                //this.propertyGrid.Refresh();


            }
            catch (Exception ex)
            {
                Debug.Assert(false, "Error in resetting portfolios " + ex.Message);
            }
        }

    }
}
